package com.study.demo.service;

import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

import com.stduy.util.AppManager;
import com.stduy.util.Logger;
import com.stduy.util.NetWorkUtil;
import com.study.demo.DemoApplication;
import com.study.demo.R;
import com.study.demo.api.forum.ForumApi;
import com.study.demo.bean.Message;
import com.study.demo.bean.MessageData;
import com.study.demo.bean.MessageResult;
import com.study.demo.components.storage.UserStorage;
import com.study.demo.injector.component.ApplicationComponent;
import com.study.demo.injector.component.DaggerServiceComponent;
import com.study.demo.injector.module.ServiceModule;
import com.study.demo.ui.messagelist.MessageActivity;
import com.study.demo.ui.splash.SplashActivity;
import com.study.demo.util.SettingPrefUtil;

import java.util.Calendar;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;


/**
 * Created by shangsong on 17-3-6.
 */

public class MessageService extends Service {

    public static final String ACTION_GET = "com.study.demo.ACTION_GET";
    public static final String ACTION_UPDATE = "com.study.demo.ACTION_UPDATE";
    public static final String ACTION_CLOSE = "com.study.demo.ACTION_CLOSE";
    public static final int REQUEST_CODE_GET = 1;

    @Inject
    UserStorage userStorage;

    @Inject
    ForumApi forumApi;
    private NotificationManager notificationManager;


    @Override
    public void onCreate() {
        super.onCreate();
        DaggerServiceComponent.builder().applicationComponent(getApplicationComponent())
                .serviceModule(new ServiceModule(this)).build().inject(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!userStorage.isLogin() || !SettingPrefUtil.getNotification(this)) {
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        if (notificationManager == null) {
            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }

        String action = intent != null ? intent.getAction() : "";

        if (ACTION_GET.equals(action)) {
            resetTheTime();
            loadMessage();
        } else if (ACTION_UPDATE.equals(action)) {
            Logger.d("刷新时间");
            resetTheTime();
        } else if (ACTION_CLOSE.equals(action)) {
            clearAlarm();
            stopSelf();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void clearAlarm() {
        AlarmManager alarManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarManager.cancel(getOperation());
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void resetTheTime() {
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.HOUR, 1);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), getOperation());
    }

    private PendingIntent getOperation() {
        Intent intent = new Intent(ACTION_GET);
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        return PendingIntent.getService(this, REQUEST_CODE_GET, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
    }

    public ApplicationComponent getApplicationComponent() {
        return ((DemoApplication) this.getApplication()).getApplicationComponent();
    }

    private void loadMessage() {
        if (NetWorkUtil.isWifiConnected(this)) {
            forumApi.getMessageList("", 1)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this::onLoadMessageSuccess, this::onLoadMessageFailed);
        }
    }

    private void onLoadMessageSuccess(MessageData messageData) {
        if (messageData != null && messageData.status == 200) {
            notifyMessageCount(messageData.result);
        }
    }

    private void onLoadMessageFailed(Throwable throwable) {
        if (throwable != null) {
            Logger.e(this.getClass() + ": load message failed, " + throwable.getMessage());
        }
    }

    public void notifyMessageCount(MessageResult result) {
        result.list.forEach(this::handleMessage);
    }

    private void handleMessage(Message message) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.drawable.ic_list_comment)
                .setContentTitle(message.info)
                .setContentText("来自TLint");
        Intent intent;
        if (AppManager.getAppManager().isAppExit()) {
            intent = new Intent(this, SplashActivity.class);
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setAction(SplashActivity.ACTION_NOTIFICATION_MESSAGE);
        } else {
            intent = new Intent(this, MessageActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        PendingIntent contentIntent =
                PendingIntent.getActivity(this, Integer.valueOf(message.id), intent,
                        PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent).setAutoCancel(true);
        builder.setTicker(message.info);

        notificationManager.notify(Integer.valueOf(message.id), builder.build());
    }
}
